from flask import render_template,redirect,url_for
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from lib.form import Form
from dao.user import UserDao
from controller import app
from service.user import LoginForm, UserService
import json

@app.route("/login")                 
@app.route("/login", methods=["GET", "POST"])
def login():
    '''When a user logs in, their session is marked as 'fresh'.
    '''
    form = LoginForm()
    if form.is_submitted():
        if form.errors == []:
            service = UserService()
            ret = service.login(form.account, form.password)
            #flash('Logged in successfully!')
            #return render_template('products.html', mytest = 'You logged in')
            #return render_template('setting.html')
            if ret:
                return render_template('index.html', username=current_user.username)
            #return redirect(request.args.get("next") or url_for("index"))
            else:
                return render_template("login.html", errors_json=[])
        else: # If input has error
            return render_template("login.html", errors_json=json.dumps(form.errors))
    else:
        return render_template("login.html", errors_json=[])
